﻿/**
 * 企业MarkerList，包含以下功能：
 * 1、左侧面板：企业列表元素自定义渲染：名称、地址、信用代码、国省市控
 * 2、分页初始化、销毁
 * 3、地图企业点位信息：自定义点位信息；弹出提示信息窗体；打开新窗口查看排污许可证信息
 * 4、地图输入框输入名称后检索企业(条件包含区域、行业、监管类型、其他条件)，展示企业左侧面板与点位
 * 5、包含的数据：
 * 1）企业的点位数据列表，查看goPage方法请求的后台JSON数据
 * 2）markerList属性，加载的MarkerList对象
 * 3）psDetailUrl，许可证详情信息URL
 * 4）inited，分页首次加载标记，false则首次调用initPagination从第一页开始渲染
 */
var EMarkerList = {
	
	$keywords: $('#sole-input'),	
		
	markerList : null,	
	
	//许可证详情URL
	psDetailUrl: Service.urlService.getUrl(),
	
	//分页初始化
	inited: false,
	
	//分页
    $pagination: $('#pagination-enterprise'),
	
	//初始化分页器
	initPagination: function(page, totalPages){
		EMarkerList.$pagination.twbsPagination({
            totalPages: totalPages,
            startPage: page,
            prev: null,
            first: '首页',
            next: '下一页',
            last: null,
            initiateStartPageClick: false,
            onPageClick: function(event, page) {
            	EMarkerList.goPage(page);
            }
        });
	},
	
	/**
	 * goPage方法为加载后台JSON数据的入口，获取数据后会重新渲染MarkerList
	 */
	goPage: function(page) {
    	var keywords = EMarkerList.$keywords.val();
    	keywords = keywords=='排污许可企业'?'':keywords;
    	var areacode = AreaLevelController.getAreaCode();
    	var codeTrade = TradeLevelController.getTradeCode();
    	var codeControllevel = ControlLevelController.getControlLevelCode();
    	var adFormData = AdvancedController.getFormParamsData();
    	//console.log(adFormData);
        ajaxProcess({
            url : '/pls/gis/enterprise/queryCompatys',
            requestType : 'POST',
            data : {
            	page: page, 
            	rows:30, 
            	companyName: keywords, 
            	areacode: areacode,
            	codeTrade:codeTrade,
            	codeControllevel:codeControllevel,
            	permitPolluteCode:adFormData.permitPolluteCode,
            	permitEmissionFrom:adFormData.permitEmissionFrom,
            	permitEmissionTo:adFormData.permitEmissionTo,
            	actualPolluteCode:adFormData.actualPolluteCode,
            	actualEmissionFrom:adFormData.actualEmissionFrom,
            	actualEmissionTo:adFormData.actualEmissionTo,
            	licenseStartYear:adFormData.startYear,
            	licenseEndYear:adFormData.endYear,
            	processTechIds:adFormData.processTechIds
            },
            successHandle : function(data) {
            	//console.log(data);
            	EMarkerList.markerList.render(data.data.list);
                
                if (!EMarkerList.inited) {
                	EMarkerList.inited = true;
                    //首次初始化
                    if(page<=data.data.pages) {
                    	EMarkerList.initPagination(page, data.data.pages);
                    }
                }
            }
        });
    },
	
    /**
     * load方法应该在初次加载MarkerList时调用,无论如何别多次调用，重新渲染请使用reRenderData
     */
	load: function(){
		EMarkerList.clearData();
		AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'],
		    function(MarkerList, SimpleMarker, SimpleInfoWindow) {

		    //即jQuery/Zepto
		    var $ = MarkerList.utils.$;

		    var defaultIconStyle = 'red', //默认的图标样式
		        hoverIconStyle = 'green', //鼠标hover时的样式
		        selectedIconStyle = 'purple' //选中时的图标样式
		    ;

		    var markerList = new MarkerList({
		        map: gis.map,
		        //ListElement对应的父节点或者ID
		        listContainer: "enterpriseList", //document.getElementById("myList"),
		        //选中后显示

		        //从数据中读取位置, 返回lngLat
		        getPosition: function(item) {
		            return [item.longitude, item.latitude];
		        	//return item.location;
		        },
		        //数据ID，如果不提供，默认使用数组索引，即index
		        getDataId: function(item, index) {

		            return item.id;
		        },
		        getInfoWindow: function(data, context, recycledInfoWindow) {
		        	//console.log("窗体"+data);
		            if (recycledInfoWindow) {

		                recycledInfoWindow.setInfoTitle(data.entername);
		                recycledInfoWindow.setInfoBody(data.enteraddress);

		                return recycledInfoWindow;
		            }

		            return new SimpleInfoWindow({
		                infoTitle: data.entername,
		                infoBody: data.enteraddress,
		                offset: new AMap.Pixel(0, -37)
		            });
		        },
		        //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
		        getMarker: function(data, context, recycledMarker) {

		            var label = context.index+1;//String.fromCharCode('A'.charCodeAt(0) + context.index);

		            if (recycledMarker) {
		                recycledMarker.setIconLabel(label);
		                return;
		            }

		            return new SimpleMarker({
		                containerClassNames: 'my-marker',
		                iconStyle: defaultIconStyle,
		                iconLabel: label
		            });
		        },
		        //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
		        getListElement: function(data, context, recycledListElement) {

		            var label = context.index+1;//String.fromCharCode('A'.charCodeAt(0) + context.index);

		            var innerHTML = MarkerList.utils.template(
		                    '<% if(data.codeControllevel == "countryControl") { %>' +
		                    '<div class="poi-imgbox">' +
		                    '    <span class="poi-img" style="background-image:url(./images/guo.png)"></span>' +
		                    '</div>' +
		                    '<% } %>' +
		                    '<% if(data.codeControllevel == "provinceControl") { %>' +
		                    '<div class="poi-imgbox">' +
		                    '    <span class="poi-img" style="background-image:url(./images/sheng.png)"></span>' +
		                    '</div>' +
		                    '<% } %>' +
		                    '<% if(data.codeControllevel == "cityControl" || !data.codeControllevel) { %>' +
		                    '<div class="poi-imgbox">' +
		                    '    <span class="poi-img" style="background-image:url(./images/shi.png)"></span>' +
		                    '</div>' +
		                    '<% } %>' +
		                    '<div class="poi-info-left">' +
		                    '    <h3 class="poi-title">' +
		                    '        <%- label %>. <%- data.entername %>' +
		                    '    </h3>' +
		                    '    <div class="poi-info">' +
		                    '        <p class="poi-addr">地址：<%- data.enteraddress %></p>' +
		                    '<% if(data.stdpscode ){ %>' +
		                    '        <p class="poi-addr">统一社会信用代码：<%- data.stdpscode %></p>' +
		                    '<% } %>' +
		                    '    </div>' +
		                    '</div>' +
		                    '<div class="clear"></div>', {
		                        data: data,
		                        label: label
		                    });

		            if (recycledListElement) {
		                recycledListElement.innerHTML = innerHTML;
		                return recycledListElement;
		            }

		            return '<li class="poibox">' +
		                innerHTML +
		                '</li>';
		        },
		        //列表节点上监听的事件
		        listElementEvents: ['click', 'mouseenter', 'mouseleave'],
		        //marker上监听的事件
		        markerEvents: ['click', 'mouseover', 'mouseout'],
		        //makeSelectedEvents:false,
		        selectedClassNames: 'selected',
		        autoSetFitView: true
		    });

		    EMarkerList.markerList = markerList;

		    EMarkerList.goPage(1);

		    markerList.on('selectedChanged', function(event, info) {

		        if (info.selected) {

		            //console.log(info);
		            if(!EMarkerList.psDetailUrl) {
		            	EMarkerList.psDetailUrl=Service.urlService.getUrl();
		            }
		            if(info.selected.data&&info.selected.data.pscode) {
		            	EMarkerList.openPSLicenseDetailWin(info.selected.data.pscode);
		            }
		            
		            if (info.selected.marker) {
		                //更新为选中样式
		                info.selected.marker.setIconStyle(selectedIconStyle);
		            }

		            //选中并非由列表节点上的事件触发，将关联的列表节点移动到视野内
		            if (!info.sourceEventInfo.isListElementEvent) {

		                if (info.selected.listElement) {
		                    scrollListElementIntoView($(info.selected.listElement));
		                }
		            }
		        }

		        if (info.unSelected && info.unSelected.marker) {
		            //更新为默认样式
		            info.unSelected.marker.setIconStyle(defaultIconStyle);
		        }
		    });

		    markerList.on('listElementMouseenter markerMouseover', function(event, record) {

		        if (record && record.marker) {

		            forcusMarker(record.marker);

		            //this.openInfoWindowOnRecord(record);

		            //非选中的id
		            if (!this.isSelectedDataId(record.id)) {
		                //设置为hover样式
		                record.marker.setIconStyle(hoverIconStyle);
		                //this.closeInfoWindow();
		            }
		        }
		    });

		    markerList.on('listElementMouseleave markerMouseout', function(event, record) {

		        if (record && record.marker) {

		            if (!this.isSelectedDataId(record.id)) {
		                //恢复默认样式
		                record.marker.setIconStyle(defaultIconStyle);
		            }
		        }
		    });

		    //数据输出完成
		    markerList.on('renderComplete', function(event, records) {

		    });

		    // markerList.on('*', function(type, event, res) {
		    //     console.log(type, event, res);
		    // });

		    function forcusMarker(marker) {
		        marker.setTop(true);

		        //不在地图视野内
		        if (!(gis.map.getBounds().contains(marker.getPosition()))) {

		            //移动到中心
		        	gis.map.setCenter(marker.getPosition());
		        }
		    }

		    function isElementInViewport(el) {
		        var rect = el.getBoundingClientRect();

		        return (
		            rect.top >= 0 &&
		            rect.left >= 0 &&
		            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
		            rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
		        );
		    }

		    function scrollListElementIntoView($listEle) {

		        if (!isElementInViewport($listEle.get(0))) {
		            $('#panel').scrollTop(($listEle.offset().top - $listEle.parent().offset().top)+'px');
		            //console.log($listEle.offset().top - $listEle.parent().offset().top);
		        }

		        //闪动一下
		        $listEle
		            .one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
		                function(e) {
		                    $(this).removeClass('flash animated');
		                }).addClass('flash animated');
		    }
		});
	},
	
	/**
	 * 销毁分页后从第一页开始渲染MarkerList
	 */
	reRenderData:function(data){
		EMarkerList.inited = false;
        EMarkerList.$pagination.twbsPagination('destroy');
        EMarkerList.goPage(1);
	},
	
	/**
	 * 清空MarkerList数据，以及销毁分页
	 */
	clearData: function(){
		EMarkerList.inited = false;
        EMarkerList.$pagination.twbsPagination('destroy');
		if(EMarkerList.markerList && EMarkerList.markerList.getData() && EMarkerList.markerList.getData().length>0) {
			EMarkerList.markerList.clearData();
		}
	},
	
	/**
	 * 打开新窗口查看排污许可证信息
	 */
	openPSLicenseDetailWin: function(pscode){
		var psDetailUrl = EMarkerList.psDetailUrl + '&PSCODE='+pscode;
    	window.open(psDetailUrl);
	}
};


/**
 * 许可证到警预期MarkerList，包含以下功能：
 * 1、地图上全省的许可证数量汇总，按到期时间区间段来划分
 * 2、左侧面板企业列表元素自定义渲染：各地市许可证到警预期企业数量；各企业许可证有效开始结束时间、是否超期
 * 3、地图点位信息：叠加echart饼状图、自定义企业点位信息
 * 4、点击地图上饼状图，渲染该地市下的企业点位信息；收缩地图后，点位信息消失、渲染饼状图
 * 5、包含的数据：
 * 1）各地市饼状图数据与企业(sublist)点位数据数组，查看goPage方法请求的后台JSON数据
 * 2）markerList属性，加载的MarkerList对象
 * 3）cityData数组，地市许可证的数量，内部对象带有arealeve标记；cityDataLength为cityData数组长度
 * 4）inited，MarkerList首次加载标记，用于cityData数组首次加载，为false则把地市的数据加到该数组中
 * 5）cityMarker数组，地市marker数组，cityDataLength与cityData的长度相同后，自定义饼状图marker不会重新生成
 * 6）sublist数组，所有企业点位数据，用于地图放大到一定级别后显示，该功能目前暂时不用
 */
var LMarkerList = {
		
	markerList : null,	
	
	//所有的自定义饼状图marker是否渲染完成的一个标记，用cityDataLength做依据来判断
	inited: false,
	
	//后台地市数据数组
	cityData: [],
	//后台地市数据数组长度
	cityDataLength: 0,
	//地市marker数组，cityDataLength与cityData的长度相同后，自定义饼状图marker不会重新生成
	cityMarker:[],
	//所有企业点位数据，用于地图放大到一定级别后显示
	sublist:[],
	
	/**
	 * goPage方法为加载后台JSON数据的入口，获取数据后会重新渲染MarkerList，从最外层的地图饼状图开始渲染
	 */
	goPage: function(page) {
		var d = new Date();
		var expireTime;
    	var year = YearController.getYearCode()?YearController.getYearCode():d.getFullYear();
    	if(year == d.getFullYear()) {
    		expireTime = year+'-'+ (d.getMonth()+1) +'-'+ d.getDate();
    		expireTime = '2020-7-12';
    	}else {
    		expireTime = year+'-12-31';
    	}
        ajaxProcess({
            url : '/pls/gis/licence/warning',
            requestType : 'POST',
            data : {
            	expireTime : expireTime
            },
            successHandle : function(res) {
            	//console.log(res);
            	
            	LMarkerList.clearData();
            	
            	var data = res.rows;
            	var t;
            	var d = [];
            	for(var i=0; i<data.length; i++) {
            		if(data[i].areaLevel=='province'){
            			t = data[i];
            		}else if(data[i].areaLevel=='city') {
            			d.push(data[i]);
            			for(var j=0; j<data[i].sublist.length;j++) {
                    		LMarkerList.sublist.push(data[i].sublist[j]);
                    	}
            		}
            	}
            	//console.log('LMarkerList goPage：');
            	//console.log(d);
            	LMarkerList.cityData = d;
            	LMarkerList.cityDataLength = d.length;
            
            	LMarkerList.renderTotal(t);
            	LMarkerList.markerList.render(d);
            }
        });
    },
	
    /**
     * load方法应该在初次加载MarkerList时调用,无论如何别多次调用，重新渲染请使用reRenderData
     */
	load: function(){
		LMarkerList.clearData();
		AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'],
		    function(MarkerList, SimpleMarker, SimpleInfoWindow) {

		    //即jQuery/Zepto
		    var $ = MarkerList.utils.$;

		    var defaultIconStyle = 'red', //默认的图标样式
		        hoverIconStyle = 'green', //鼠标hover时的样式
		        selectedIconStyle = 'purple' //选中时的图标样式
		    ;

		    var markerList = new MarkerList({
		        map: gis.map,
		        //ListElement对应的父节点或者ID
		        listContainer: "enterpriseList",
		        //选中后显示

		        //从数据中读取位置, 返回lngLat
		        getPosition: function(item) {
		            return [item.longitude, item.latitude];
		        	//return item.location;
		        },
		        //数据ID，如果不提供，默认使用数组索引，即index
		        getDataId: function(item, index) {

		            return item.id;
		        },
		        getInfoWindow: function(data, context, recycledInfoWindow) {
		        	//console.log("窗体"+data);
		        	
		        	if(!data.areaLevel){
			            
			        	var infoTitle = data.entername + ((data.warningLevel == "pastdue")?'：超期':'：未超期');
			        	var infoBody =  '<div class="poi-info-left">' +
					                    '    <h3 class="poi-title">' +
					                    '    </h3>' +
					                    '    <div class="poi-info">' +
					                    '        <p class="poi-addr">有效开始时间：'+data.stime + '</p>' +
					                    '        <p class="poi-addr">有效结束时间：'+data.etime + '</p>' +
					                    '    </div>' +
					                    '</div>' +
					                    '<div class="clear"></div>';

			            return new SimpleInfoWindow({
			                infoTitle: infoTitle,
			                infoBody:  infoBody,
			                offset: new AMap.Pixel(0, -37)
			            });
		        	}
		        	
		        	var infoTitle = data.regionname + '：许可证到期预警数量（单位：个）';
		        	var infoBody =  '<div class="poi-info-left">' +
				                    '    <h3 class="poi-title">' +
				                    '    </h3>' +
				                    '    <div class="poi-info">' +
				                    '        <p class="poi-addr">超期：'+data.pastDueNum+'&nbsp;&nbsp;&nbsp;&nbsp;1个月：'+data.onePastDueNum+'&nbsp;&nbsp;&nbsp;&nbsp;2个月：'+data.twoPastDueNum + '</p>' +
				                    '        <p class="poi-addr">3个月：'+data.threePastDueNum + '&nbsp;&nbsp;&nbsp;&nbsp;6个月：'+ data.sixPastDueNum + '&nbsp;&nbsp;&nbsp;&nbsp;6个月以上：'+data.gtSixPastDueNum + '</p>' +
				                    '    </div>' +
				                    '</div>' +
				                    '<div class="clear"></div>';
		            if (recycledInfoWindow) {

		                recycledInfoWindow.setInfoTitle(infoTitle);
		                recycledInfoWindow.setInfoBody(infoBody);

		                return recycledInfoWindow;
		            }

		            return new SimpleInfoWindow({
		                infoTitle: infoTitle,
		                infoBody:  infoBody,
		                offset: new AMap.Pixel(0, -37)
		            });
		        },
		        //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
		        getMarker: function(data, context, recycledMarker) {
		        	//console.log('地区级别：'+data.areaLevel);
		        	//console.log('getMarker：'+data);
		            var label = context.index+1;//String.fromCharCode('A'.charCodeAt(0) + context.index);
		            /*
		            if (recycledMarker) {
		                recycledMarker.setIconLabel(label);
		                return;
		            }
		           */
		        	
		        	if(!data.areaLevel){
			            return new SimpleMarker({
			                containerClassNames: 'my-marker',
			                iconStyle: defaultIconStyle,
			                iconLabel: label
			            });
		        	}
		        	
		        	if(LMarkerList.cityMarker && LMarkerList.inited) {
		        		return LMarkerList.cityMarker[context.index];
		        	}
		        	return LMarkerList.createCustomMarker(data, context.index);
		        },
		        //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
		        getListElement: function(data, context, recycledListElement) {

		            var label = context.index+1;
		            
		            
		            if(!data.areaLevel){
		            	var innerHTML = MarkerList.utils.template(
			                    '<div class="poi-info-left">' +
			                    '    <h3 class="poi-title">' +
			                    '        <%- label %>. <%- data.entername %>' + "：" +
			                    '			<% if(data.warningLevel == "pastdue") { %>' +
			                    ''				+ '超期' +
			                    '			<% } %>'+
			                    '			<% if(data.warningLevel != "pastdue") { %>' +
			                    ''				+ '未超期' +
			                    '			<% } %>'+
			                    '    </h3>' +
			                    '    <div class="poi-info">' +
			                    '        <p class="poi-addr">地址：<%- data.enteraddress %></p>' +
			                    '        <p class="poi-addr">许可证有效开始结束时间：<%- data.stime %>至<%- data.etime %></p>' +
			                    '    </div>' +
			                    '</div>' +
			                    '<div class="clear"></div>', {
			                        data: data,
			                        label: label
			                    });

			            return 	'<li class="poibox">' +
				                innerHTML +
				                '</li>';
		        	}

		            //./images/guo.png
		            var innerHTML = MarkerList.utils.template(
		                    '<div class="poi-info-left">' +
		                    '    <h3 class="poi-title">' +
		                    '        <%- label %>. <%- data.regionname %>' + '：许可证到期预警数量（单位：个）' + 
		                    '    </h3>' +
		                    '    <div class="poi-info">' +
		                    '        <p class="poi-addr">超期：<%- data.pastDueNum %>&nbsp;&nbsp;&nbsp;&nbsp;1个月：<%- data.onePastDueNum %>&nbsp;&nbsp;&nbsp;&nbsp;2个月：<%- data.twoPastDueNum %></p>' +
		                    '        <p class="poi-addr">3个月：<%- data.threePastDueNum %>&nbsp;&nbsp;&nbsp;&nbsp;6个月：<%- data.sixPastDueNum %>&nbsp;&nbsp;&nbsp;&nbsp;6个月以上：<%- data.gtSixPastDueNum %></p>' +
		                    '    </div>' +
		                    '</div>' +
		                    '<div class="clear"></div>', {
		                        data: data,
		                        label: label
		                    });

		            if (recycledListElement) {
		                recycledListElement.innerHTML = innerHTML;
		                return recycledListElement;
		            }

		            return 	'<li class="poibox">' +
			                innerHTML +
			                '</li>';
		        },
		        //列表节点上监听的事件
		        listElementEvents: ['click', 'mouseenter', 'mouseleave'],
		        //marker上监听的事件
		        markerEvents: ['click', 'mouseover', 'mouseout'],
		        //makeSelectedEvents:false,
		        selectedClassNames: 'selected',
		        autoSetFitView: true
		    });

		    //window.markerList = markerList;
		    LMarkerList.markerList = markerList;

		    LMarkerList.goPage(1);
		    
		    AMap.event.addListener(gis.map, 'zoomend', LMarkerList._onZoomEnd);

		    markerList.on('selectedChanged', function(event, info) {

		        if (info.selected) {

		            //console.log(info);
		            
		            if (info.selected.marker) {
		                //更新为选中样式
		                //info.selected.marker.setIconStyle(selectedIconStyle);
		            }

		            //选中并非由列表节点上的事件触发，将关联的列表节点移动到视野内
		            if (!info.sourceEventInfo.isListElementEvent) {

		                if (info.selected.listElement) {
		                    scrollListElementIntoView($(info.selected.listElement));
		                }
		            }
		        }

		        if (info.unSelected && info.unSelected.marker) {
		            //更新为默认样式
		            //info.unSelected.marker.setIconStyle(defaultIconStyle);
		        }
		    });

		    markerList.on('listElementMouseenter markerMouseover', function(event, record) {

		        if (record && record.marker) {

		            forcusMarker(record.marker);

		            //this.openInfoWindowOnRecord(record);

		            //非选中的id
		            if (!this.isSelectedDataId(record.id)) {
		                //设置为hover样式
		                //record.marker.setIconStyle(hoverIconStyle);
		                //this.closeInfoWindow();
		            }
		        }
		    });

		    markerList.on('listElementMouseleave markerMouseout', function(event, record) {

		        if (record && record.marker) {

		            if (!this.isSelectedDataId(record.id)) {
		                //恢复默认样式
		                //record.marker.setIconStyle(defaultIconStyle);
		            }
		        }
		    });

		    //数据输出完成
		    markerList.on('renderComplete', function(event, records) {

		    });

		    // markerList.on('*', function(type, event, res) {
		    //     console.log(type, event, res);
		    // });

		    function forcusMarker(marker) {
		        marker.setTop(true);

		        //不在地图视野内
		        if (!(gis.map.getBounds().contains(marker.getPosition()))) {

		            //移动到中心
		        	gis.map.setCenter(marker.getPosition());
		        }
		    }

		    function isElementInViewport(el) {
		        var rect = el.getBoundingClientRect();

		        return (
		            rect.top >= 0 &&
		            rect.left >= 0 &&
		            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
		            rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
		        );
		    }

		    function scrollListElementIntoView($listEle) {

		        if (!isElementInViewport($listEle.get(0))) {
		            $('#panel').scrollTop(($listEle.offset().top - $listEle.parent().offset().top)+'px');
		            //console.log($listEle.offset().top - $listEle.parent().offset().top);
		        }

		        //闪动一下
		        $listEle
		            .one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
		                function(e) {
		                    $(this).removeClass('flash animated');
		                }).addClass('flash animated');
		    }
		});
	},
	
	/**
	 * 重新渲染MarkerList
	 */
	reRenderData:function(data){
		LMarkerList.goPage(1);
	},
	
	/**
	 * 1、销毁MarkerList
	 * LMarkerList下的数据cityData、cityMarker、sublist只是简单重置，已使用的内存不一定得到释放
	 * 2、全省的许可证数量汇总面板，被清空
	 */
	clearData: function(){
		console.log('销毁LMarkerList：'+LMarkerList.markerList);
		if(LMarkerList.markerList && LMarkerList.markerList.getData() && LMarkerList.markerList.getData().length>0) {
			LMarkerList.markerList.clearData();
			
			LMarkerList.inited = false;
			LMarkerList.cityData = [];
			LMarkerList.cityDataLength = 0;
			LMarkerList.cityMarker = [];
			LMarkerList.sublist = [];
		}
		if($('#warmTotal').length>0) {
			$('#totalLicenseContent').html("");
		}
	},
	
	/**
	 * 许可证到期预警汇总
	 */
	renderTotal:function(data){
		AMapUI.loadUI(['misc/MarkerList'], function(MarkerList) {
			var totalList = '<ul id="warmTotal">'+
								'<li>'+
								'<div class="n-icon01 icon-list on"><span>超期：<a href="#">'+data.pastDueNum+'</a></span></div>'+
								'</li>'+
								'<li>'+
									'<div class="n-icon02 icon-list on"><span>1个月内：<a href="#">'+data.onePastDueNum+'</a></span></div>'+
								'</li>'+
								'<li><div class="n-icon03 icon-list on"><span>2个月内：<a href="#">'+data.twoPastDueNum+'</a></span></div></li>'+
								'<li><div class="n-icon04 icon-list on"><span>3个月内：<a href="#">'+data.threePastDueNum+'</a></span></div></li>'+
								'<li>'+
									'<div class="n-icon05 icon-list on"><span>6个月内：<a href="#">'+data.sixPastDueNum+'</a></span></div>'+
								'</li>'+
								'<li>'+
									'<div class="n-icon05 icon-list on"><span>6个月以上：<a href="#">'+data.gtSixPastDueNum+'</a></span></div>'+
								'</li>'+
							'</ul>';
			var html = MarkerList.utils.template(totalList, {data: data});  
			$("#totalLicenseContent").html("").html(html); 
		});
	},
	
	/**
	 * 点位颜色样式：根据预警时间段的不同
	 */
	markerStyle : function(data) {
	    var r;
        if(data.warningLevel=='pastdue') {
        	r = '#EE3B3B';
        }else if(data.warningLevel=='onePastDue'){
        	r = '#EEB422';
        }else if(data.warningLevel=='twoPastDue'){
        	r = '#FFD39B';
        }else if(data.warningLevel=='threePastDue'){
        	r = '#EEE685';
        }else if(data.warningLevel=='sixPastDue'){
        	r = '#98FB98';
        }else if(data.warningLevel=='gtSixPastDue'){
        	r = '#00CD00';
        }else {
        	r = '#00CD00';
        }
	    return r;
	},
	
	 /**
     * 地图上的收缩响应事件，重新渲染饼状图，清掉企业点位
     */
	_onZoomEnd : function(e) {
        if (gis.map.getZoom() <= 8) {
        	//这里要检查一下地图是否已经存在数据了，存在不应该重新渲染了
        	LMarkerList.markerList.render(LMarkerList.cityData);
        }/*else {
        	//地图放大会多次进入该方法...出现错乱渲染
        	LMarkerList.markerList.render(LMarkerList.sublist);
        }*/
    },
    
    /**
     * 地图上的饼状图点击响应事件，渲染该地市下面的企业点位信息，清掉饼状图
     */
    _onClick : function(e) {
    	console.log(e);
    	console.log(e.target.getExtData());
    	LMarkerList.markerList.render(e.target.getExtData());
    },
    
	/** 
	 * 添加自定义标注 
	 */  
	createCustomMarker: function(data, divNumber){    
		/** 
	     * 自定义覆盖物dom元素   
	     */ 
	    var div = document.createElement("div");    
	    div.id = 'div'+divNumber;  
	    div.style.width = "76px";  
	    div.style.height = "76px";  
	    divNumber++;  
	      
	    var marker = new AMap.Marker({    
	        map:gis.map,
	        position:new AMap.LngLat(data.longitude, data.latitude), //基点位置    
	        offset: new AMap.Pixel(-5, 5),
	        //draggable:true,  //是否可拖动    
	        content:div   //自定义覆盖物内容    
	    });  
	    
	    if(!LMarkerList.inited && LMarkerList.cityDataLength>LMarkerList.cityMarker.length){
	    	LMarkerList.cityMarker.push(marker);
	    }
	    if(LMarkerList.cityDataLength == LMarkerList.cityMarker.length){
	    	LMarkerList.inited = true;
	    }
	    marker.setExtData(data.sublist);
	    AMap.event.addListener(marker, 'click', LMarkerList._onClick);
	    
	    gis.map.getContainer().appendChild(div); //这句代码是关键,就是添加一个可引用的div,否则在echarts做图时会抛出找不多div节点的错误
	    LMarkerList.createPie(div.id,data);
        return marker;
	},
	
	 /** 
     * 添加饼图 
     */  
	createPie: function(divId, data) {
	    // 基于准备好的dom，初始化echarts图表
        var myChart = echarts.init(document.getElementById(divId)); 
        
        var option = {
    	    tooltip : {
    	        trigger: 'item',
    	        formatter: "{a} <br/>{b} : {c} ({d}%)",
    	        backgroundColor:'#fff',
    	        textStyle: {
    	        	color: '#333'
    	        }
    	    },
    	    series : [
    	        {
    	            name: '许可证到期预警数量',
    	            type: 'pie',
    	            radius : '70%',
    	            center: ['50%', '50%'],
    	            data:[
    	                {value:data.pastDueNum, name:'超期', itemStyle: {normal: {color: '#EE3B3B'}} },
    	                {value:data.onePastDueNum, name:'1个月内', itemStyle: {normal: {color: '#EEB422'}} },
    	                {value:data.twoPastDueNum, name:'2个月内', itemStyle: {normal: {color: '#FFD39B'}} },
    	                {value:data.threePastDueNum, name:'3个月内', itemStyle: {normal: {color: '#EEE685'}} },
    	                {value:data.sixPastDueNum, name:'6个月内', itemStyle: {normal: {color: '#98FB98'}} },
    	                {value:data.gtSixPastDueNum, name:'6个月以上', itemStyle: {normal: {color: '#00CD00'}} }
    	            ],
    	            itemStyle: {
    	                emphasis: {
    	                    shadowBlur: 10,
    	                    shadowOffsetX: 0,
    	                    shadowColor: 'rgba(0, 0, 0, 0.5)'
    	                },
    	                normal: {
    	                    label:{show:false}
    	                }
    	            }
    	        }
    	    ]
    	};

        // 为echarts对象加载数据 
        myChart.setOption(option); 
	}
};

/**
 * 排口MarkerList，包含以下功能：
 * 1、左侧面板：排口列表元素自定义渲染：编号、名称、企业、地址、行业、排污类型（废气废水）
 * 2、分页初始化、销毁
 * 3、地图排口点位信息：自定义点位信息；选择排口打开窗口查看排口信息
 * 4、地图输入框输入编号或者名称后检索排口(条件包含区域、行业、监管类型、排污类型)，展示企业左侧面板与点位
 * 5、包含的数据：
 * 1）排口的点位数据列表，查看goPage方法请求的后台JSON数据
 * 2）markerList属性，加载的MarkerList对象
 * 3）inited，分页首次加载标记，false则首次调用initPagination从第一页开始渲染
 */
var PMarkerList = {
	
	$keywords: $('#sole-input'),	
		
	markerList : null,	
	
	//分页初始化
	inited: false,
	
	//分页
    $pagination: $('#pagination-enterprise'),
	
	//初始化分页器
	initPagination: function(page, totalPages){
		PMarkerList.$pagination.twbsPagination({
            totalPages: totalPages,
            startPage: page,
            prev: null,
            first: '首页',
            next: '下一页',
            last: null,
            initiateStartPageClick: false,
            onPageClick: function(event, page) {
            	PMarkerList.goPage(page);
            }
        });
	},
	
	/**
	 * goPage方法为加载后台JSON数据的入口，获取数据后会重新渲染MarkerList
	 */
	goPage: function(page) {
    	var keywords = PMarkerList.$keywords.val();
    	keywords = keywords=='排污许可企业'?'':keywords;
    	var areacode = AreaLevelController.getAreaCode();
    	var codeTrade = TradeLevelController.getTradeCode();
    	var pointType = ControlLevelController.getControlLevelCode();
    	//console.log(adFormData);
        ajaxProcess({
            url : '/pls/gis/point/bycondition',
            requestType : 'POST',
            data : {
            	page: page, 
            	rows:30, 
            	pointCode: keywords, 
            	areacode: areacode,
            	codeTrade:codeTrade,
            	pointType:pointType
            },
            successHandle : function(data) {
            	//console.log(data);
            	PMarkerList.renderTotal(data.data.pointquantity);
            	PMarkerList.markerList.render(data.data.listPoint);
                
                if (!PMarkerList.inited) {
                	PMarkerList.inited = true;
                    //首次初始化
                    if(page<=data.data.pages) {
                    	PMarkerList.initPagination(page, data.data.pages);
                    }
                }
            }
        });
    },
	
    /**
     * load方法应该在初次加载MarkerList时调用,无论如何别多次调用，重新渲染请使用reRenderData
     */
	load: function(){
		PMarkerList.clearData();
		AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'],
		    function(MarkerList, SimpleMarker, SimpleInfoWindow) {

		    //即jQuery/Zepto
		    var $ = MarkerList.utils.$;

		    var defaultIconStyle = 'red', //默认的图标样式
		        hoverIconStyle = 'green', //鼠标hover时的样式
		        selectedIconStyle = 'purple' //选中时的图标样式
		    ;

		    var markerList = new MarkerList({
		        map: gis.map,
		        //ListElement对应的父节点或者ID
		        listContainer: "enterpriseList", //document.getElementById("myList"),
		        //选中后显示

		        //从数据中读取位置, 返回lngLat
		        getPosition: function(item) {
		            return [item.longitude, item.latitude];
		        	//return item.location;
		        },
		        //数据ID，如果不提供，默认使用数组索引，即index
		        getDataId: function(item, index) {

		            return item.id;
		        },
		        getInfoWindow: function(data, context, recycledInfoWindow) {
		        	//console.log("窗体"+data);
		        	var div = '<div>'+
		        				'<p>编号：'+data.pointcode+'</p>'+
		        				'<p>企业：'+data.entername+'</p>'+
		        			  '</div>';
		            if (recycledInfoWindow) {

		                recycledInfoWindow.setInfoTitle(data.pointname);
		                recycledInfoWindow.setInfoBody(div);

		                return recycledInfoWindow;
		            }

		            return new SimpleInfoWindow({
		                infoTitle: data.pointname,
		                infoBody: div,
		                offset: new AMap.Pixel(0, -37)
		            });
		        },
		        //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
		        getMarker: function(data, context, recycledMarker) {

		            var label = context.index+1;//String.fromCharCode('A'.charCodeAt(0) + context.index);

		            if (recycledMarker) {
		                recycledMarker.setIconLabel(label);
		                return;
		            }

		            return new SimpleMarker({
		                containerClassNames: 'my-marker',
		                iconStyle: defaultIconStyle,
		                iconLabel: label
		            });
		        },
		        //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
		        getListElement: function(data, context, recycledListElement) {

		            var label = context.index+1;//String.fromCharCode('A'.charCodeAt(0) + context.index);

		            //./images/guo.png
		            var innerHTML = MarkerList.utils.template(
		                    '<% if(data.pointType == "air") { %>' +
		                    '<div class="poi-imgbox">' +
		                    '    <span class="poi-img" style="background-image:url(./images/sheng.png)"></span>' +
		                    '</div>' +
		                    '<% } %>' +
		                    '<% if(data.pointType == "water") { %>' +
		                    '<div class="poi-imgbox">' +
		                    '    <span class="poi-img" style="background-image:url(./images/shi.png)"></span>' +
		                    '</div>' +
		                    '<% } %>' +
		                    '<div class="poi-info-left">' +
		                    '    <h3 class="poi-title">' +
		                    '        <%- label %>. <%- data.pointname %>' +
		                    '    </h3>' +
		                    '    <div class="poi-info">' +
		                    '        <p class="poi-addr">排口编号：<%- data.pointcode %></p>' +
		                    '        <p class="poi-addr">企业：<%- data.entername %></p>' +
		                    '    </div>' +
		                    '</div>' +
		                    '<div class="clear"></div>', {
		                        data: data,
		                        label: label
		                    });

		            if (recycledListElement) {
		                recycledListElement.innerHTML = innerHTML;
		                return recycledListElement;
		            }

		            return '<li class="poibox">' +
		                innerHTML +
		                '</li>';
		        },
		        //列表节点上监听的事件
		        listElementEvents: ['click', 'mouseenter', 'mouseleave'],
		        //marker上监听的事件
		        markerEvents: ['click', 'mouseover', 'mouseout'],
		        //makeSelectedEvents:false,
		        selectedClassNames: 'selected',
		        autoSetFitView: true
		    });

		    PMarkerList.markerList = markerList;

		    PMarkerList.goPage(1);

		    markerList.on('selectedChanged', function(event, info) {

		        if (info.selected) {

		            console.log(info);
		            
		            if(info.selected.data) {
		            	var param = {
		            		pointcode:info.selected.data.pointcode,
		            		pointname:info.selected.data.pointname,
		            		pointType:info.selected.data.pointType
		            	};
		            	PMarkerList.openPointDetailWin(param);
		            }
		            
		            if (info.selected.marker) {
		                //更新为选中样式
		                info.selected.marker.setIconStyle(selectedIconStyle);
		            }

		            //选中并非由列表节点上的事件触发，将关联的列表节点移动到视野内
		            if (!info.sourceEventInfo.isListElementEvent) {

		                if (info.selected.listElement) {
		                    scrollListElementIntoView($(info.selected.listElement));
		                }
		            }
		        }

		        if (info.unSelected && info.unSelected.marker) {
		            //更新为默认样式
		            info.unSelected.marker.setIconStyle(defaultIconStyle);
		        }
		    });

		    markerList.on('listElementMouseenter markerMouseover', function(event, record) {

		        if (record && record.marker) {

		            forcusMarker(record.marker);

		            //this.openInfoWindowOnRecord(record);

		            //非选中的id
		            if (!this.isSelectedDataId(record.id)) {
		                //设置为hover样式
		                record.marker.setIconStyle(hoverIconStyle);
		                //this.closeInfoWindow();
		            }
		        }
		    });

		    markerList.on('listElementMouseleave markerMouseout', function(event, record) {

		        if (record && record.marker) {

		            if (!this.isSelectedDataId(record.id)) {
		                //恢复默认样式
		                record.marker.setIconStyle(defaultIconStyle);
		            }
		        }
		    });

		    //数据输出完成
		    markerList.on('renderComplete', function(event, records) {

		    });

		    // markerList.on('*', function(type, event, res) {
		    //     console.log(type, event, res);
		    // });

		    function forcusMarker(marker) {
		        marker.setTop(true);

		        //不在地图视野内
		        if (!(gis.map.getBounds().contains(marker.getPosition()))) {

		            //移动到中心
		        	gis.map.setCenter(marker.getPosition());
		        }
		    }

		    function isElementInViewport(el) {
		        var rect = el.getBoundingClientRect();

		        return (
		            rect.top >= 0 &&
		            rect.left >= 0 &&
		            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
		            rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
		        );
		    }

		    function scrollListElementIntoView($listEle) {

		        if (!isElementInViewport($listEle.get(0))) {
		            $('#panel').scrollTop(($listEle.offset().top - $listEle.parent().offset().top)+'px');
		            //console.log($listEle.offset().top - $listEle.parent().offset().top);
		        }

		        //闪动一下
		        $listEle
		            .one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
		                function(e) {
		                    $(this).removeClass('flash animated');
		                }).addClass('flash animated');
		    }
		});
	},
	
	/**
	 * 销毁分页后从第一页开始渲染MarkerList
	 */
	reRenderData:function(data){
		PMarkerList.inited = false;
		PMarkerList.$pagination.twbsPagination('destroy');
		PMarkerList.goPage(1);
	},
	
	/**
	 * 清空MarkerList数据，以及销毁分页
	 */
	clearData: function(){
		PMarkerList.inited = false;
		PMarkerList.$pagination.twbsPagination('destroy');
		if(PMarkerList.markerList && PMarkerList.markerList.getData() && PMarkerList.markerList.getData().length>0) {
			PMarkerList.markerList.clearData();
		}
		if($('#pointTotal').length>0) {
			$('#totalPointContent').html("");
		}
		PDCard.hide();
	},
	
	/**
	 * 排污口废气废水数量汇总
	 */
	renderTotal:function(data){
		AMapUI.loadUI(['misc/MarkerList'], function(MarkerList) {
			var totalList = '<ul id="pointTotal">'+
								'<li>'+
								'<div class="n-icon01 icon-list on"><span>废气：<a href="#">'+data.airpointquantity+'</a></span></div>'+
								'</li>'+
								'<li>'+
									'<div class="n-icon02 icon-list on"><span>废水：<a href="#">'+data.waterpointquantity+'</a></span></div>'+
								'</li>'+
							'</ul>';
			var html = MarkerList.utils.template(totalList, {data: data});  
			$("#totalPointContent").html("").html(html); 
		});
	},
	
	/**
	 * 打开窗口查看排口信息
	 */
	openPointDetailWin: function(param){
		PDCard.renderTab(param);
	}
};


/**
 * 排放量MarkerList，包含以下功能：
 * 1、地图上全省的许可证数量汇总，按到期时间区间段来划分
 * 2、左侧面板企业列表元素自定义渲染：各地市许可证到警预期企业数量；各企业许可证有效开始结束时间、是否超期
 * 3、地图点位信息：叠加echart饼状图、自定义企业点位信息
 * 4、点击地图上饼状图，渲染该地市下的企业点位信息；收缩地图后，点位信息消失、渲染饼状图
 * 5、包含的数据：
 * 1）各地市饼状图数据与企业(sublist)点位数据数组，查看goPage方法请求的后台JSON数据
 * 2）markerList属性，加载的MarkerList对象
 * 3）cityData数组，地市许可证的数量，内部对象带有arealeve标记；cityDataLength为cityData数组长度
 * 4）inited，MarkerList首次加载标记，用于cityData数组首次加载，为false则把地市的数据加到该数组中
 * 5）cityMarker数组，地市marker数组，cityDataLength与cityData的长度相同后，自定义饼状图marker不会重新生成
 * 6）sublist数组，所有企业点位数据，用于地图放大到一定级别后显示，该功能目前暂时不用
 */
var ESMarkerList = {
		
	markerList : null,	
	
	//所有的自定义饼状图marker是否渲染完成的一个标记，用cityDataLength做依据来判断
	inited: false,
	
	//后台地市数据数组
	cityData: [],
	//后台地市数据数组长度
	cityDataLength: 0,
	//地市marker数组，cityDataLength与cityData的长度相同后，自定义饼状图marker不会重新生成
	cityMarker:[],
	//所有企业点位数据，用于地图放大到一定级别后显示
	sublist:[],
	
	/**
	 * goPage方法为加载后台JSON数据的入口，获取数据后会重新渲染MarkerList，从最外层的地图饼状图开始渲染
	 */
	goPage: function(page) {
		var d = new Date();
		var expireTime;
    	var year = YearController.getYearCode()?YearController.getYearCode():d.getFullYear();
    	if(year == d.getFullYear()) {
    		expireTime = year+'-'+ (d.getMonth()+1) +'-'+ d.getDate();
    		expireTime = '2020-7-12';
    	}else {
    		expireTime = year+'-12-31';
    	}
        ajaxProcess({
            url : '/pls/gis/licence/warning',
            requestType : 'POST',
            data : {
            	expireTime : expireTime
            },
            successHandle : function(res) {
            	//console.log(res);
            	
            	ESMarkerList.clearData();
            	
            	var data = res.rows;
            	var t;
            	var d = [];
            	for(var i=0; i<data.length; i++) {
            		if(data[i].areaLevel=='province'){
            			t = data[i];
            		}else if(data[i].areaLevel=='city') {
            			d.push(data[i]);
            			for(var j=0; j<data[i].sublist.length;j++) {
            				ESMarkerList.sublist.push(data[i].sublist[j]);
                    	}
            		}
            	}
            	//console.log('LMarkerList goPage：');
            	//console.log(d);
            	ESMarkerList.cityData = d;
            	ESMarkerList.cityDataLength = d.length;
            
            	ESMarkerList.markerList.render(d);
            }
        });
    },
	
    /**
     * load方法应该在初次加载MarkerList时调用,无论如何别多次调用，重新渲染请使用reRenderData
     */
	load: function(){
		ESMarkerList.clearData();
		AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'],
		    function(MarkerList, SimpleMarker, SimpleInfoWindow) {

		    //即jQuery/Zepto
		    var $ = MarkerList.utils.$;

		    var defaultIconStyle = 'red', //默认的图标样式
		        hoverIconStyle = 'green', //鼠标hover时的样式
		        selectedIconStyle = 'purple' //选中时的图标样式
		    ;

		    var markerList = new MarkerList({
		        map: gis.map,
		        //ListElement对应的父节点或者ID
		        listContainer: "enterpriseList",
		        //选中后显示

		        //从数据中读取位置, 返回lngLat
		        getPosition: function(item) {
		            return [item.longitude, item.latitude];
		        	//return item.location;
		        },
		        //数据ID，如果不提供，默认使用数组索引，即index
		        getDataId: function(item, index) {

		            return item.id;
		        },
		        getInfoWindow: function(data, context, recycledInfoWindow) {
		        	//console.log("窗体"+data);
		        	
		        	if(!data.areaLevel){
			            
			        	var infoTitle = data.entername + ((data.warningLevel == "pastdue")?'：超期':'：未超期');
			        	var infoBody =  '<div class="poi-info-left">' +
					                    '    <h3 class="poi-title">' +
					                    '    </h3>' +
					                    '    <div class="poi-info">' +
					                    '        <p class="poi-addr">有效开始时间：'+data.stime + '</p>' +
					                    '        <p class="poi-addr">有效结束时间：'+data.etime + '</p>' +
					                    '    </div>' +
					                    '</div>' +
					                    '<div class="clear"></div>';

			            return new SimpleInfoWindow({
			                infoTitle: infoTitle,
			                infoBody:  infoBody,
			                offset: new AMap.Pixel(0, -37)
			            });
		        	}
		        	
		        	var infoTitle = data.regionname + '：许可证到期预警数量（单位：个）';
		        	var infoBody =  '<div class="poi-info-left">' +
				                    '    <h3 class="poi-title">' +
				                    '    </h3>' +
				                    '    <div class="poi-info">' +
				                    '        <p class="poi-addr">超期：'+data.pastDueNum+'&nbsp;&nbsp;&nbsp;&nbsp;1个月：'+data.onePastDueNum+'&nbsp;&nbsp;&nbsp;&nbsp;2个月：'+data.twoPastDueNum + '</p>' +
				                    '        <p class="poi-addr">3个月：'+data.threePastDueNum + '&nbsp;&nbsp;&nbsp;&nbsp;6个月：'+ data.sixPastDueNum + '&nbsp;&nbsp;&nbsp;&nbsp;6个月以上：'+data.gtSixPastDueNum + '</p>' +
				                    '    </div>' +
				                    '</div>' +
				                    '<div class="clear"></div>';
		            if (recycledInfoWindow) {

		                recycledInfoWindow.setInfoTitle(infoTitle);
		                recycledInfoWindow.setInfoBody(infoBody);

		                return recycledInfoWindow;
		            }

		            return new SimpleInfoWindow({
		                infoTitle: infoTitle,
		                infoBody:  infoBody,
		                offset: new AMap.Pixel(0, -37)
		            });
		        },
		        //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
		        getMarker: function(data, context, recycledMarker) {
		        	//console.log('地区级别：'+data.areaLevel);
		        	//console.log('getMarker：'+data);
		            var label = context.index+1;//String.fromCharCode('A'.charCodeAt(0) + context.index);
		            /*
		            if (recycledMarker) {
		                recycledMarker.setIconLabel(label);
		                return;
		            }
		           */
		        	
		        	if(!data.areaLevel){
			            return new SimpleMarker({
			                containerClassNames: 'my-marker',
			                iconStyle: defaultIconStyle,
			                iconLabel: label
			            });
		        	}
		        	
		        	if(ESMarkerList.cityMarker && ESMarkerList.inited) {
		        		return ESMarkerList.cityMarker[context.index];
		        	}
		        	return ESMarkerList.createCustomMarker(data, context.index);
		        },
		        //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
		        getListElement: function(data, context, recycledListElement) {

		            var label = context.index+1;
		            
		            
		            if(!data.areaLevel){
		            	var innerHTML = MarkerList.utils.template(
			                    '<div class="poi-info-left">' +
			                    '    <h3 class="poi-title">' +
			                    '        <%- label %>. <%- data.entername %>' + "：" +
			                    '			<% if(data.warningLevel == "pastdue") { %>' +
			                    ''				+ '超期' +
			                    '			<% } %>'+
			                    '			<% if(data.warningLevel != "pastdue") { %>' +
			                    ''				+ '未超期' +
			                    '			<% } %>'+
			                    '    </h3>' +
			                    '    <div class="poi-info">' +
			                    '        <p class="poi-addr">地址：<%- data.enteraddress %></p>' +
			                    '        <p class="poi-addr">许可证有效开始结束时间：<%- data.stime %>至<%- data.etime %></p>' +
			                    '    </div>' +
			                    '</div>' +
			                    '<div class="clear"></div>', {
			                        data: data,
			                        label: label
			                    });

			            return 	'<li class="poibox">' +
				                innerHTML +
				                '</li>';
		        	}

		            //./images/guo.png
		            var innerHTML = MarkerList.utils.template(
		                    '<div class="poi-info-left">' +
		                    '    <h3 class="poi-title">' +
		                    '        <%- label %>. <%- data.regionname %>' + '：许可证到期预警数量（单位：个）' + 
		                    '    </h3>' +
		                    '    <div class="poi-info">' +
		                    '        <p class="poi-addr">超期：<%- data.pastDueNum %>&nbsp;&nbsp;&nbsp;&nbsp;1个月：<%- data.onePastDueNum %>&nbsp;&nbsp;&nbsp;&nbsp;2个月：<%- data.twoPastDueNum %></p>' +
		                    '        <p class="poi-addr">3个月：<%- data.threePastDueNum %>&nbsp;&nbsp;&nbsp;&nbsp;6个月：<%- data.sixPastDueNum %>&nbsp;&nbsp;&nbsp;&nbsp;6个月以上：<%- data.gtSixPastDueNum %></p>' +
		                    '    </div>' +
		                    '</div>' +
		                    '<div class="clear"></div>', {
		                        data: data,
		                        label: label
		                    });

		            if (recycledListElement) {
		                recycledListElement.innerHTML = innerHTML;
		                return recycledListElement;
		            }

		            return 	'<li class="poibox">' +
			                innerHTML +
			                '</li>';
		        },
		        //列表节点上监听的事件
		        listElementEvents: ['click', 'mouseenter', 'mouseleave'],
		        //marker上监听的事件
		        markerEvents: ['click', 'mouseover', 'mouseout'],
		        //makeSelectedEvents:false,
		        selectedClassNames: 'selected',
		        autoSetFitView: true
		    });

		    //window.markerList = markerList;
		    ESMarkerList.markerList = markerList;

		    ESMarkerList.goPage(1);
		    
		    AMap.event.addListener(gis.map, 'zoomend', ESMarkerList._onZoomEnd);

		    markerList.on('selectedChanged', function(event, info) {

		        if (info.selected) {

		            //console.log(info);
		            
		            if (info.selected.marker) {
		                //更新为选中样式
		                //info.selected.marker.setIconStyle(selectedIconStyle);
		            }

		            //选中并非由列表节点上的事件触发，将关联的列表节点移动到视野内
		            if (!info.sourceEventInfo.isListElementEvent) {

		                if (info.selected.listElement) {
		                    scrollListElementIntoView($(info.selected.listElement));
		                }
		            }
		        }

		        if (info.unSelected && info.unSelected.marker) {
		            //更新为默认样式
		            //info.unSelected.marker.setIconStyle(defaultIconStyle);
		        }
		    });

		    markerList.on('listElementMouseenter markerMouseover', function(event, record) {

		        if (record && record.marker) {

		            forcusMarker(record.marker);

		            //this.openInfoWindowOnRecord(record);

		            //非选中的id
		            if (!this.isSelectedDataId(record.id)) {
		                //设置为hover样式
		                //record.marker.setIconStyle(hoverIconStyle);
		                //this.closeInfoWindow();
		            }
		        }
		    });

		    markerList.on('listElementMouseleave markerMouseout', function(event, record) {

		        if (record && record.marker) {

		            if (!this.isSelectedDataId(record.id)) {
		                //恢复默认样式
		                //record.marker.setIconStyle(defaultIconStyle);
		            }
		        }
		    });

		    //数据输出完成
		    markerList.on('renderComplete', function(event, records) {

		    });

		    // markerList.on('*', function(type, event, res) {
		    //     console.log(type, event, res);
		    // });

		    function forcusMarker(marker) {
		        marker.setTop(true);

		        //不在地图视野内
		        if (!(gis.map.getBounds().contains(marker.getPosition()))) {

		            //移动到中心
		        	gis.map.setCenter(marker.getPosition());
		        }
		    }

		    function isElementInViewport(el) {
		        var rect = el.getBoundingClientRect();

		        return (
		            rect.top >= 0 &&
		            rect.left >= 0 &&
		            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
		            rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
		        );
		    }

		    function scrollListElementIntoView($listEle) {

		        if (!isElementInViewport($listEle.get(0))) {
		            $('#panel').scrollTop(($listEle.offset().top - $listEle.parent().offset().top)+'px');
		            //console.log($listEle.offset().top - $listEle.parent().offset().top);
		        }

		        //闪动一下
		        $listEle
		            .one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
		                function(e) {
		                    $(this).removeClass('flash animated');
		                }).addClass('flash animated');
		    }
		});
	},
	
	/**
	 * 重新渲染MarkerList
	 */
	reRenderData:function(data){
		ESMarkerList.goPage(1);
	},
	
	/**
	 * 1、销毁MarkerList
	 * LMarkerList下的数据cityData、cityMarker、sublist只是简单重置，已使用的内存不一定得到释放
	 * 2、全省的许可证数量汇总面板，被清空
	 */
	clearData: function(){
		console.log('销毁LMarkerList：'+LMarkerList.markerList);
		if(ESMarkerList.markerList && ESMarkerList.markerList.getData() && ESMarkerList.markerList.getData().length>0) {
			ESMarkerList.markerList.clearData();
			
			ESMarkerList.inited = false;
			ESMarkerList.cityData = [];
			ESMarkerList.cityDataLength = 0;
			ESMarkerList.cityMarker = [];
			ESMarkerList.sublist = [];
		}
	},
	
	/**
	 * 点位颜色样式：根据预警时间段的不同
	 */
	markerStyle : function(data) {
	    var r;
        if(data.warningLevel=='pastdue') {
        	r = '#EE3B3B';
        }else if(data.warningLevel=='onePastDue'){
        	r = '#EEB422';
        }else if(data.warningLevel=='twoPastDue'){
        	r = '#FFD39B';
        }else if(data.warningLevel=='threePastDue'){
        	r = '#EEE685';
        }else if(data.warningLevel=='sixPastDue'){
        	r = '#98FB98';
        }else if(data.warningLevel=='gtSixPastDue'){
        	r = '#00CD00';
        }else {
        	r = '#00CD00';
        }
	    return r;
	},
	
	 /**
     * 地图上的收缩响应事件，重新渲染饼状图，清掉企业点位
     */
	_onZoomEnd : function(e) {
        if (gis.map.getZoom() <= 8) {
        	//这里要检查一下地图是否已经存在数据了，存在不应该重新渲染了
        	LMarkerList.markerList.render(LMarkerList.cityData);
        }/*else {
        	//地图放大会多次进入该方法...出现错乱渲染
        	LMarkerList.markerList.render(LMarkerList.sublist);
        }*/
    },
    
    /**
     * 地图上的饼状图点击响应事件，渲染该地市下面的企业点位信息，清掉饼状图
     */
    _onClick : function(e) {
    	console.log(e);
    	console.log(e.target.getExtData());
    	ESMarkerList.markerList.render(e.target.getExtData());
    },
    
	/** 
	 * 添加自定义标注 
	 */  
	createCustomMarker: function(data, divNumber){    
		/** 
	     * 自定义覆盖物dom元素   
	     */ 
	    var div = document.createElement("div");    
	    div.id = 'div'+divNumber;  
	    div.style.width = "76px";  
	    div.style.height = "76px";  
	    divNumber++;  
	      
	    var marker = new AMap.Marker({    
	        map:gis.map,
	        position:new AMap.LngLat(data.longitude, data.latitude), //基点位置    
	        offset: new AMap.Pixel(-5, 5),
	        //draggable:true,  //是否可拖动    
	        content:div   //自定义覆盖物内容    
	    });  
	    
	    if(!ESMarkerList.inited && ESMarkerList.cityDataLength>LMarkerList.cityMarker.length){
	    	ESMarkerList.cityMarker.push(marker);
	    }
	    if(ESMarkerList.cityDataLength == ESMarkerList.cityMarker.length){
	    	ESMarkerList.inited = true;
	    }
	    marker.setExtData(data.sublist);
	    AMap.event.addListener(marker, 'click', ESMarkerList._onClick);
	    
	    gis.map.getContainer().appendChild(div); //这句代码是关键,就是添加一个可引用的div,否则在echarts做图时会抛出找不多div节点的错误
	    ESMarkerList.createPie(div.id,data);
        return marker;
	},
	
	 /** 
     * 添加饼图 
     */  
	createPie: function(divId, data) {
	    // 基于准备好的dom，初始化echarts图表
        var myChart = echarts.init(document.getElementById(divId)); 
        
        var option = {
    	    tooltip : {
    	        trigger: 'item',
    	        formatter: "{a} <br/>{b} : {c} ({d}%)",
    	        backgroundColor:'#fff',
    	        textStyle: {
    	        	color: '#333'
    	        }
    	    },
    	    series : [
    	        {
    	            name: '许可证到期预警数量',
    	            type: 'pie',
    	            radius : '70%',
    	            center: ['50%', '50%'],
    	            data:[
    	                {value:data.pastDueNum, name:'超期', itemStyle: {normal: {color: '#EE3B3B'}} },
    	                {value:data.onePastDueNum, name:'1个月内', itemStyle: {normal: {color: '#EEB422'}} },
    	                {value:data.twoPastDueNum, name:'2个月内', itemStyle: {normal: {color: '#FFD39B'}} },
    	                {value:data.threePastDueNum, name:'3个月内', itemStyle: {normal: {color: '#EEE685'}} },
    	                {value:data.sixPastDueNum, name:'6个月内', itemStyle: {normal: {color: '#98FB98'}} },
    	                {value:data.gtSixPastDueNum, name:'6个月以上', itemStyle: {normal: {color: '#00CD00'}} }
    	            ],
    	            itemStyle: {
    	                emphasis: {
    	                    shadowBlur: 10,
    	                    shadowOffsetX: 0,
    	                    shadowColor: 'rgba(0, 0, 0, 0.5)'
    	                },
    	                normal: {
    	                    label:{show:false}
    	                }
    	            }
    	        }
    	    ]
    	};

        // 为echarts对象加载数据 
        myChart.setOption(option); 
	}
};

/**
 * 销毁所有MarkerList的数据及渲染效果
 * @returns
 */
function clearAllMarkerList() {
	EMarkerList.clearData();
	LMarkerList.clearData();
	PMarkerList.clearData();
	ESMarkerList.clearData();
}